package controllers;

import java.util.*;

import dto.api.ApiAuthInfoDto;
import dto.retjson.*;

import org.codehaus.jackson.JsonNode;
import play.libs.*;
import play.mvc.*;
import play.mvc.Http.*;
import services.api.*;
import services.exception.AniNeedApprovalException;
import utils.*;

public class ApiCallingController extends BaseController{

    public static Result callApi(Long clientAppId, Long targetApiId, Long reqId,
			String authCode){
        JsonNode result = null;
		try{
            ApiAuthInfoDto apiAuthInfo = new ApiAuthInfoDto(
                    clientAppId,
                    targetApiId,
                    reqId,
                    authCode);
            Map<String, String> params = MVCUtils.getRequestArgs(Context.current().request());
            result = Json.parse(
                    AniApiCallingService.callApiWithAppRel(apiAuthInfo, params)
                    );
        }catch (Exception e){
            Integer retCode = 1;
            if(e instanceof AniNeedApprovalException){
                retCode = 2;
            }
            return internalServerError(
                    Json.toJson(
                            new RetDataDto(false, String.valueOf(retCode), e.getMessage())
                    )
            );
        }
    	return ok(
                Json.toJson(
                        new RetDataDto(true, "0", result)
                )
        );
    }
}
